<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ProductImageController extends Controller
{
    /**
     * Upload a product image and return its relative path
     *
     * @param Request $request
     * @return array
     */
    public function add(Request $request)
    {
        try {
            // Validate the request
            $validator = Validator::make($request->all(), [
                'file' => 'required|file|image|max:20480', // Max 20MB
            ]);

            if ($validator->fails()) {
                Log::warning('ProductImageController: Image upload validation failed', [
                    'errors' => $validator->errors()->all(),
                ]);
                return [
                    'status' => 'error',
                    'error' => $validator->errors()->first(),
                ];
            }

            // Get the uploaded file and save path
            $file = $request->file('file');

            // Ensure the save path is clean and relative
            $savePath = ''; // Default directory if none provided

            // Get the original filename and store the file
            $originName = $file->getClientOriginalName();
            $filePath = $file->storeAs($savePath, $originName, 'catalog');

            // Check if the file was stored successfully
            if (!$filePath) {
                Log::error('ProductImageController: Failed to store image', [
                    'filename' => $originName,
                    'path' => $savePath,
                ]);
                return [
                    'status' => 'error',
                    'error' => 'Failed to store image',
                ];
            }

            // Generate the relative path
            $relativePath = 'catalog/product/' . $filePath;

            Log::info('ProductImageController: Image uploaded successfully', [
                'filename' => $originName,
                'relative_path' => $relativePath,
            ]);

            return [
                'status' => 'success',
                'name' => $originName,
                'path' => $relativePath,
            ];

        } catch (\Exception $e) {
            Log::error('ProductImageController: Exception during image upload', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            return [
                'status' => 'error',
                'error' => 'Image upload failed: ' . $e->getMessage(),
            ];
        }
    }
}